﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Emporium_Web.Controls;
using Emporium_Web.Enums;
using Emporium_Web.DBML;
using System.Linq.Expressions;

namespace Emporium_Web
{
    public partial class PackingList : System.Web.UI.Page
    {
        public string SortExpression
        {
            get
            {
                return ViewState["gv_SortExpression"] == null ? "" : ViewState["gv_SortExpression"].ToString();
            }
            set
            {
                ViewState["gv_SortExpression"] = value;
            }
        }

        public string SortDirection
        {
            get
            {
                return ViewState["gv_SortDirection"] == null ? "" : ViewState["gv_SortDirection"].ToString();
            }
            set
            {
                ViewState["gv_SortDirection"] = value;
            }
        }

        private int IdSeleccionado
        {
            get { return (int)ViewState["IdSeleccionado"]; }
            set { }
        }

        /// <summary>
        /// Los componentes.
        /// </summary>
        private List<PackingContador> PackingContadorList
        {
            get
            {
                return ViewState["PackingContadorList"] == null ? null : (List<PackingContador>)ViewState["PackingContadorList"];
            }
            set
            {
                ViewState["PackingContadorList"] = value;
            }
        }

        [Serializable]
        private class PackingContador
        {
            public int CodigoPacking { get; set; }
            public int TotalPrendas { get; set; }            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Master.ActualizaMenu(MenuPrincipal.Produccion, (int)MenuProduccion.PackingList);
                Master.AgregarBreadcrumb("Packing List", "#", true);
                Master.AgregarBreadcrumb("Listado", "#", false);

                warningMessage.Visible = false;
                errorMessage.Visible = false;
                lblMensajeGridFooter.Text = String.Format(Resources.MensajesValidacion.GridFooterMessage, 0);

                PackingContadorList = new List<PackingContador>();
                ListarPackings();
            }
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                ListarPackings();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnAdicionar_Click(object sender, EventArgs e)
        {
            Response.Redirect("PackingForm.aspx?Operacion=" + (int)AccionesForm.Adicionar);
        }

        protected void btnModificar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("PackingForm.aspx?Operacion=" + (int)AccionesForm.Modificar + "&PackingId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnEditarDetalle_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("PackingDetalle.aspx?Operacion=" + (int)AccionesForm.Modificar + "&PackingId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }      

        protected void btnEliminar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Eliminar();
                    ListarPackings();
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }        

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(((LinkButton)sender).Text, out codigo))
                {
                    Response.Redirect("PackingForm.aspx?Operacion=" + (int)AccionesForm.Consultar + "&PackingId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        private void Eliminar()
        {
            int OrdenCorteId = 0;
            if (Int32.TryParse(hdnSeleccion.Value.ToString(), out OrdenCorteId))
            {
                TablasDataContext database = new TablasDataContext();                

                database.SubmitChanges();
                hdnSeleccion.Value = "";
            }
            else
            {
                warningMessage.Visible = true;
                lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
            }
        }       

        protected void gvPagerPageChanged(object sender, DataNavigatorEventArgs e)
        {
            ListarPackings();
        }

        private void ListarPackings()
        {
            TablasDataContext database = new TablasDataContext();

            int codPacking = txtNroPacking.Text == string.Empty ? 0 : Convert.ToInt32(txtNroPacking.Text);
            int codPedidoCompra = txtNroPedidoCompra.Text == string.Empty ? 0 : Convert.ToInt32(txtNroPedidoCompra.Text);

            var listarQuery = from packings in database.PR_PackingList
                              where (packings.PacLis_Id == codPacking || codPacking == 0)
                                 && (packings.PedCom_Id == codPedidoCompra || codPedidoCompra == 0)
                              select packings;

            var listaContadores = from detalles in database.PR_OrdenCortePaquete
                                  group detalles by detalles.OrdCor_Id into g
                                  select new
                                  {
                                      CodigoPedido = g.Key,
                                      PrendasSolicitadas = g.Sum(c => c.OrdCorPaq_Prendas)
                                  };

            foreach (var item in listaContadores)
            {
                PackingContadorList.Add(new PackingContador()
                {
                    CodigoPacking = item.CodigoPedido,
                    TotalPrendas = Convert.ToInt32(item.PrendasSolicitadas)
                });
            }

            listarQuery = OrdenarQuery(listarQuery);

            var listarQuery1 = listarQuery.Skip((gvPager.CurrentPage - 1) * gvPager.PageSize).Take(gvPager.PageSize).ToList();

            gvPackings.DataSource = listarQuery1;
            gvPackings.DataBind();

            int totalReg = listarQuery.Count();

            if (totalReg > 0)
            {
                gvPackings.UseAccessibleHeader = false;
                gvPackings.HeaderRow.TableSection = TableRowSection.TableHeader;
                gvPager.Visible = true;
                gvPager.TotalRowCount = totalReg;
                warningMessage.Visible = false;
            }
            else
            {
                lblWarningMessage.Text = Resources.MensajesValidacion.NoDataFound;
                warningMessage.Visible = true;
                gvPager.Visible = false;
            }

            lblMensajeGridFooter.Text = String.Format(Resources.MensajesValidacion.GridFooterMessage, totalReg);
            ActivaIconoOrdenamiento();
        }

        private void ActivaIconoOrdenamiento()
        {
            if (gvPackings.HeaderRow == null)
            {
                return;
            }

            LinkButton lnkSender = null;
            LinkButton lnkSortDown = null;
            LinkButton lnkSortUp = null;

            if (this.SortDirection != null && this.SortDirection.ToUpper().Equals("ASC"))
            {
                lnkSender = (LinkButton)gvPackings.HeaderRow.FindControl("lnkSortUp" + this.SortExpression);
                if (lnkSender != null)
                    lnkSortDown = (LinkButton)gvPackings.HeaderRow.FindControl(lnkSender.ID.Replace("SortUp", "SortDown"));
                if (lnkSortUp != null) lnkSortDown.CssClass = "sort-down";
                if (lnkSender != null) lnkSender.CssClass = "sort-up active";
            }
            else
            {
                lnkSender = (LinkButton)gvPackings.HeaderRow.FindControl("lnkSortDown" + this.SortExpression);
                if (lnkSender != null)
                    lnkSortUp = (LinkButton)gvPackings.HeaderRow.FindControl(lnkSender.ID.Replace("SortDown", "SortUp"));

                if (lnkSortUp != null) lnkSortUp.CssClass = "sort-up";
                if (lnkSender != null) lnkSender.CssClass = "sort-down active";
            }
        }

        protected void gvPackings_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var paquete = (PR_PackingList)(e.Row.DataItem);

                Label lblEstado = (Label)e.Row.FindControl("lblEstado");
                if (lblEstado != null && lblEstado.Text != string.Empty)
                {
                    lblEstado.Text = lblEstado.Text == "A" ? "ACTIVO" : "CERRADO";
                }

                if (PackingContadorList.Count > 0 && PackingContadorList.Find(c => c.CodigoPacking == paquete.PacLis_Id) != null)
                {
                    Label lblTotasPrendas = (Label)e.Row.FindControl("lblTotasPrendas");
                    if (lblTotasPrendas != null && lblTotasPrendas.Text == string.Empty)
                    {
                        lblTotasPrendas.Text = PackingContadorList.Find(c => c.CodigoPacking == paquete.PacLis_Id).TotalPrendas.ToString();
                    }
                }
            }            
        }


        private IQueryable<PR_PackingList> OrdenarQuery(IQueryable<PR_PackingList> listarQuery)
        {
            if (this.SortExpression == null || this.SortExpression.Trim().Equals(""))
            {
                this.SortExpression = "Packing";
            }

            if (this.SortDirection == null || this.SortDirection.Trim().Equals(""))
            {
                this.SortDirection = "DES";
            }

            if (this.SortExpression == "Packing")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.PacLis_Id);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.PacLis_Id);
                }
            }
            else if (this.SortExpression == "PedidoCompra")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.PedCom_Id);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.PedCom_Id);
                }
            }
            else if (this.SortExpression == "Despacho")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.PacLis_Despacho);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.PacLis_Despacho);
                }
            }
            else if (this.SortExpression == "Fecha")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.PacLis_Fecha);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.PacLis_Fecha);
                }
            }
            else if (this.SortExpression == "Descripcion")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.PacLis_Descripcion);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.PacLis_Descripcion);
                }
            }
            else if (this.SortExpression == "Cliente")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.CO_PedidoCompra.TG_Cliente.Nombre);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.CO_PedidoCompra.TG_Cliente.Nombre);
                }
            }
            else if (this.SortExpression == "Estado")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.PacLis_Estado);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.PacLis_Estado);
                }
            } 

            return listarQuery;
        }

        protected void gvPackings_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (gvPackings.HeaderRow == null)
                {
                    return;
                }

                this.SortExpression = e.CommandArgument != null ? e.CommandArgument.ToString() : "Id";
                this.SortDirection = e.CommandName.Equals("SortUp") ? "ASC" : "DES";

                ListarPackings();

            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnBuscarEstilo_Click(object sender, EventArgs e)
        {
            
        }

        protected void estiloAdd_Seleccionado(object sender, EventArgs e)
        {
            
        }       
    }
}